package simplechat;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;


/**
 * Serves as a datastore for the registration of nicknames.
 * @author shokora
 *
 */
public class NickServDB implements Serializable
{
	/**
	 * 
	 */
	private static final long serialVersionUID = -5379645887470127245L;
	private HashMap<String,Integer> nickDB = new HashMap<String,Integer>();
	private HashMap<Integer,String> accountDB = new HashMap<Integer,String>();
	Random generator;
	
	public NickServDB()
	{
		generator = new Random(15929423);
	}
	
	public void createInitialAccount(String nickname, String password)
	{
		int accountNumber = generator.nextInt();
		addNicknameToAccount(nickname,accountNumber);
		accountDB.put(accountNumber,password);
	}
	
	public void addNicknameToAccount(String nickname, int accountNumber)
	{
		nickDB.put(nickname, accountNumber);
	}
	
	public boolean checkPassword(String nickname, String password)
	{
		int accountNumber = nickDB.get(nickname);
		String savedPassword = accountDB.get(accountNumber);
		
		return savedPassword.equals(password);
	}
	
	public boolean checkIfRegistered(String nickname)
	{
		return nickDB.containsKey(nickname);
	}
	
	public void deleteNicknameFromAccount(String nickname)
	{
		int accountNumber = nickDB.get(nickname);
		nickDB.remove(nickname);
		if(!nickDB.containsValue(accountNumber))
		{
			accountDB.remove(accountNumber);
		}
	}
	
	public void changeAccountNumber(String nickname, int accountNumber)
	{
		nickDB.remove(nickname);
		nickDB.put(nickname, accountNumber);
	}
	
	public boolean checkIfOwnerOfNick(String nickname, String nickToRegister)
	{
		return nickDB.get(nickname).equals(nickDB.get(nickToRegister));
	}
	
	public int getAccountNumber(String nickname)
	{
		return nickDB.get(nickname);
	}
}
